from PyQt5.QtWidgets import QMainWindow, QFileDialog
from NNclient.Ui_ZFNetwin import Ui_ZFNetwin
from NNclient.myQThread import FC_HDRM_Work
from Data_Pack import myPack


class MyMainWindow(QMainWindow, Ui_ZFNetwin):
    def __init__(self, args, parent=None):
        # 窗口初始化
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)
        # 针对既定参数进行填入
        if len(args.host):
            self.LE_serverIP.setText(args.host)
        self.SB_serverPort.setValue(args.port)
        # 构建通信线程模型
        self.myWork = FC_HDRM_Work()
        # 连接线程信号
        self.myWork.sig_confin.connect(self.Con_finish)
        self.myWork.sig_dsfin.connect(self.Dset_finish)
        self.myWork.sig_samfin.connect(self.Sam_finish)
        self.myWork.sig_wffin.connect(self.Wf_finish)
        self.myWork.sig_nno1fin.connect(self.NNo1_finish)
        self.myWork.sig_nns1fin.connect(self.NNs1_finish)
        self.myWork.sig_nngs1fin.connect(self.NNgs1_finish)
        self.myWork.sig_nngd1fin.connect(self.NNgd1_finish)
        self.myWork.sig_nno2fin.connect(self.NNo2_finish)
        self.myWork.sig_nns2fin.connect(self.NNs2_finish)
        self.myWork.sig_nngd2fin.connect(self.NNgd2_finish)

    def closeEvent(self, event):
        if self.myWork.tcp_on:
            self.myWork.tcp_text = {'cmd': 'close'}
            self.myWork.sc_c.sendall(myPack(self.myWork.tcp_text))
            self.myWork.sc_c.close()
        event.accept()

    def Interact_ena(self, ena=True):
        ena1 = ena and self.myWork.tcp_on
        ena2 = ena1 and self.myWork.dset_on
        ena3 = ena2 and (not self.myWork.nn_workon)
        ena4 = ena2 and (self.myWork.nn_a1_ok or self.myWork.nn_l1_ok)
        ena5 = ena1 and (not self.myWork.nn_workon)
        ena6 = ena2 and (self.myWork.nn_a2_ok or self.myWork.nn_l2_ok)
        # 一般交互
        self.PB_connect.setEnabled(ena)
        self.PB_dload.setEnabled(ena5)
        self.CB_setchoice.setEnabled(ena3)
        self.SB_imagecount.setEnabled(ena3)
        self.PB_swfile.setEnabled(ena3)
        self.PB_lwfile.setEnabled(ena3)
        # 操作模式1
        self.PB_nnopa1.setEnabled(ena2)
        self.PB_nno1stop.setEnabled(ena2)
        self.PB_getstate1.setEnabled(ena2)
        self.PB_getdata1.setEnabled(ena2)
        self.SB_depoch1.setEnabled(ena4)
        # 操作模式2
        self.PB_nnopa2.setEnabled(ena2)
        self.PB_nno2stop.setEnabled(ena2)
        self.PB_getdata2.setEnabled(ena2)
        self.SB_depoch2.setEnabled(ena6)

    def Con_clicked(self):
        self.Interact_ena(False)
        if self.myWork.tcp_on:
            self.LE_state.setText('正在断开……')
        else:
            self.LE_state.setText('正在连接……')
            self.LE_serverIP.setEnabled(False)
            self.SB_serverPort.setEnabled(False)
            self.myWork.tcp_ip = self.LE_serverIP.text()
            self.myWork.tcp_port = self.SB_serverPort.value()
        self.myWork.thr_state = 1
        self.myWork.start()

    def Con_finish(self):
        if self.myWork.tcp_on:
            self.PB_connect.setText('断开')
        else:
            self.PB_connect.setText('连接')
            self.LE_serverIP.setEnabled(True)
            self.SB_serverPort.setEnabled(True)
        self.LE_state.setText(str(self.myWork.thr_msg))
        self.LE_state.home(False)
        self.Interact_ena(True)

    def Dload_clicked(self):
        self.Interact_ena(False)
        self.LE_state.setText('正在发送载入指令……')
        self.myWork.dset_path = self.LE_droot.text()
        self.myWork.thr_state = 2
        self.myWork.start()

    def Dset_finish(self):
        if self.myWork.dset_on:
            self.LE_dtrain.setText(self.myWork.tcp_text['strain'])
            self.LE_dtest.setText(self.myWork.tcp_text['stest'])
            self.LE_dvalid.setText(self.myWork.tcp_text['svalid'])
            self.Schoice_activated(self.CB_setchoice.currentIndex())
        self.LE_state.setText(str(self.myWork.thr_msg))
        self.LE_state.home(False)
        self.Interact_ena(True)

    def Schoice_activated(self, dsindex):
        self.Interact_ena(False)
        if dsindex == 0:
            self.SB_imagecount.setMaximum(self.myWork.dset_ltrain - 1)
        elif dsindex == 1:
            self.SB_imagecount.setMaximum(self.myWork.dset_ltest - 1)
        elif dsindex == 2:
            self.SB_imagecount.setMaximum(self.myWork.dset_lvalid - 1)
        self.myWork.sam_index = dsindex
        self.myWork.sam_count = self.SB_imagecount.value()
        self.myWork.sam_fromS = False
        self.myWork.thr_state = 3
        self.myWork.start()

    def Icount_vchanged(self, dscount):
        self.Interact_ena(False)
        self.myWork.sam_index = self.CB_setchoice.currentIndex()
        self.myWork.sam_count = dscount
        self.myWork.sam_fromS = True
        self.myWork.thr_state = 3
        self.myWork.start()

    def Sam_finish(self):
        if self.myWork.sam_ok:
            self.L_image.setPixmap(self.myWork.sam_img)
            self.LE_sampletar.setText(self.myWork.sam_str)
        else:
            self.LE_state.setText(str(self.myWork.thr_msg))
            self.LE_state.home(False)
        self.Interact_ena(True)
        if self.myWork.sam_fromS:
            self.SB_imagecount.setFocus()

    def Sdir_clicked(self):
        wfile = QFileDialog.getSaveFileName(
            self, '选择保存位置', './', '所有文件(*.*)')[0]
        self.LE_swfile.setText(wfile)

    def Swfile_clicked(self):
        self.Interact_ena(False)
        self.LE_state.setText('正在请求权重文件……')
        self.myWork.nn_wsave = True
        self.myWork.nn_wpath = self.LE_swfile.text()
        self.myWork.thr_state = 4
        self.myWork.start()

    def Ldir_clicked(self):
        wfile = QFileDialog.getOpenFileName(
            self, '选择读取位置', './', '所有文件(*.*)')[0]
        self.LE_lwfile.setText(wfile)

    def Lwfile_clicked(self):
        self.Interact_ena(False)
        self.LE_state.setText('正在读取权重文件……')
        self.myWork.nn_wsave = False
        self.myWork.nn_wpath = self.LE_lwfile.text()
        self.myWork.thr_state = 4
        self.myWork.start()

    def Wf_finish(self):
        self.LE_state.setText(str(self.myWork.thr_msg))
        self.LE_state.home(False)
        self.Interact_ena(True)

    def NNo1_clicked(self):
        self.Interact_ena(False)
        self.LE_nnstate.setText('正在请求神经网络运作（模式1）……')
        self.myWork.nno1_dset = self.CB_nno1dset.currentIndex()
        self.myWork.nno1_back = self.CHB_nno1back.isChecked()
        self.myWork.nno1_acur = self.CHB_nno1acur.isChecked()
        self.myWork.nno1_epoch = self.SB_nno1epoch.value()
        self.myWork.nno1_loss = self.CHB_nno1loss.isChecked()
        self.myWork.nn_ostate = 1
        self.myWork.thr_state = 5
        self.myWork.start()

    def NNo1_finish(self):
        self.LE_nnstate.setText(str(self.myWork.thr_msg))
        self.LE_nnstate.home(False)
        self.Interact_ena(True)

    def NNs1_clicked(self):
        self.Interact_ena(False)
        self.LE_nnstate.setText('正在请求神经网络中止（模式1）……')
        self.myWork.thr_state = 6
        self.myWork.start()

    def NNs1_finish(self):
        self.LE_nnstate.setText(str(self.myWork.thr_msg))
        self.LE_nnstate.home(False)
        self.Interact_ena(True)

    def NNgs1_clicked(self):
        self.Interact_ena(False)
        self.LE_nnstate.setText('正在获取网络状态……')
        self.myWork.thr_state = 7
        self.myWork.start()

    def NNgs1_finish(self):
        self.LE_nnstate.setText(str(self.myWork.thr_msg))
        self.LE_nnstate.home(False)
        self.Interact_ena(True)

    def NNgd1_clicked(self):
        self.Interact_ena(False)
        self.LE_nnstate.setText('正在获取网络数据（模式1）……')
        self.myWork.thr_state = 8
        self.myWork.start()

    def NNgd1_finish(self):
        self.LE_nnstate.setText(str(self.myWork.thr_msg))
        self.LE_nnstate.home(False)
        if self.myWork.nn_a1_ok or self.myWork.nn_l1_ok:
            self.SB_depoch1.setMaximum(self.myWork.a1_depoch)
            self.SB_depoch1.setValue(1)
            self.De1_vchanged(self.SB_depoch1.value())
        self.Interact_ena(True)

    def De1_vchanged(self, decount):
        if self.myWork.nn_a1_ok:
            for i in range(2):
                self.TW_nnacr1.item(0, i).setText('{:d}'.format(self.myWork.a1_nums[decount - 1][i]))
                self.TW_nnacr1.item(1, i).setText('{:d}'.format(self.myWork.a1_cors[decount - 1][i]))
                self.TW_nnacr1.item(2, i).setText('{:.2f}%'.format(self.myWork.a1_rates[decount - 1][i] * 100.00))
        if self.myWork.nn_l1_ok:
            self.LE_nnloss1.setText('{:.4f}'.format(self.myWork.a1_losses[decount - 1]))

    def NNo2_clicked(self):
        self.Interact_ena(False)
        self.LE_nnstate.setText('正在请求神经网络运作（模式2）……')
        self.myWork.nn_ostate = 2
        self.myWork.thr_state = 9
        self.myWork.start()

    def NNo2_finish(self):
        self.LE_nnstate.setText(str(self.myWork.thr_msg))
        self.LE_nnstate.home(False)
        self.Interact_ena(True)

    def NNs2_clicked(self):
        self.Interact_ena(False)
        self.LE_nnstate.setText('正在请求神经网络中止（模式2）……')
        self.myWork.thr_state = 10
        self.myWork.start()

    def NNs2_finish(self):
        self.LE_nnstate.setText(str(self.myWork.thr_msg))
        self.LE_nnstate.home(False)
        self.Interact_ena(True)

    def NNgd2_clicked(self):
        self.Interact_ena(False)
        self.LE_nnstate.setText('正在获取网络数据（模式2）……')
        self.myWork.thr_state = 11
        self.myWork.start()

    def NNgd2_finish(self):
        self.LE_nnstate.setText(str(self.myWork.thr_msg))
        self.LE_nnstate.home(False)
        if self.myWork.nn_a2_ok or self.myWork.nn_l2_ok:
            self.SB_depoch2.setMaximum(self.myWork.a2_depoch)
            self.SB_depoch2.setValue(1)
            self.De2_vchanged(self.SB_depoch2.value())
        self.Interact_ena(True)

    def De2_vchanged(self, decount):
        if self.myWork.nn_a2_ok:
            for i in range(6):
                self.TW_nnacr2.item(0, i).setText('{:d}'.format(self.myWork.a2_nums[decount - 1][i]))
                self.TW_nnacr2.item(1, i).setText('{:d}'.format(self.myWork.a2_cors[decount - 1][i]))
                self.TW_nnacr2.item(2, i).setText('{:.2f}%'.format(self.myWork.a2_rates[decount - 1][i] * 100.00))
        if self.myWork.nn_l2_ok:
            self.LE_nnloss2.setText('{:.4f}'.format(self.myWork.a2_losses[decount - 1]))
